package com.example.tangyee.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.tangyee.R;
import com.example.tangyee.bean.KnowledgeItem;
import com.example.tangyee.utils.HttpUtil;
import com.example.tangyee.utils.JsoupFilterHTML;
import com.example.tangyee.view.ProgressWebView;
import com.google.gson.Gson;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.util.LinkedHashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * @author: yu huawen
 * @date: 2019/1/28 9:31
 */
public class KnowledgeDetailActicity extends AppCompatActivity {

    private int requestParamValue;
    private String titleString;
    private KnowledgeItem knowledgeItem;
    private ProgressWebView progressWebView;
    private Handler httpHandler;
    private LinearLayout backView;
    private TextView titleView;

    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acticity_knowledge_detail);

        // 得到传来的值
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        requestParamValue = bundle.getInt("knowID");
        titleString = bundle.getString("topTitle");

        initDetailPageTitle();

        loadKnowledge();
        progressWebView = (ProgressWebView) findViewById(R.id.webview);
        httpHandler = new Handler(){
            /**
             * 收到加载成功的通知，显示页面，如果加载失败，该页面的进度条将一直不前进
             * @param msg
             */
            @Override
            public void handleMessage(Message msg) {
                Document document = Jsoup.parse(getHtmlData(knowledgeItem));
                // 使用 Jsoup 对指定标签的 Style 进行过滤
                JsoupFilterHTML.jsoupFilterStyle(document, "p>span", "white-space", "normal");
                System.out.print(document);
                progressWebView.loadDataWithBaseURL(null, document.toString(), "text/html", "utf-8", null);
            }
        };
    }

    private void initDetailPageTitle(){
        backView = (LinearLayout) findViewById(R.id.knowledge_detail_back);
        titleView = (TextView) findViewById(R.id.knowledge_detail_title);

        backView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        titleView.setText(titleString);
    }

    /**
     * 网络请求，加载知识详情
     */
    private void loadKnowledge(){
        // 设置 get 请求的参数（page, pageSize）
        LinkedHashMap<String, String> params = new LinkedHashMap<>();
        params.put("kid", requestParamValue + "");

        HttpUtil.sendRequest("https://www.tangyee.com/Mobile/Knowledge/GetKnowledgeInfo", params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            /**
             * 这里不在 UI 线程里面
             * @param call
             * @param response
             * @throws IOException
             */
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 使用轻量级的Gson解析得到的json
                String responseData = response.body().string();
                //Type listType = new TypeToken<List<KnowledgeItem>>(){}.getType();
                Gson gson = new Gson();
                knowledgeItem = gson.fromJson(responseData, KnowledgeItem.class);

                // 通知加载成功
                Message message = httpHandler.obtainMessage();
                httpHandler.sendMessage(message);

            }
        });
    }

    /**
     * 加载html标签
     *
     * @param knowledgeItem
     * @return
     */
    private String getHtmlData(KnowledgeItem knowledgeItem) {
        String head =
                "<head>" +
                        "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                        "<style>img{max-width: 100%; width:auto; height:auto!important;}</style>" +
                        "<style>" +
                            ".pb-mt15{margin-top:15px; <!--text-align: right; margin-right:10px;--> margin-bottom:15px; <!--margin-left:20px;-->}" +
                            ".pb-size-tiny{font-size:12px;}" +
                            ".meta{line-height:12px}" +
                            ".at{margin-left:15px;}" +
                            ".vw i{background-position:0 0 }" +
                            "" +
                        "</style>" +
                "</head>";
        return "<html>" +
                      head +
                      "<body style=\"word-wrap:break-word; background:#F3F3F3; \">" +
                            "<div style=\"clear: both; content: .; display: block;\">" +
                                  "<h3 style=\"border-left: thick solid #21aa8e; color:#21aa8e; padding-left:10px; margin-bottom:15px; margin-top:15px; \">" +
                                  knowledgeItem.getTitle() +
                                  "</h3>" +
                            "</div>" +
                            "<div class=\"pb-mt15 pb-size-tiny meta\" style=\"margin-bottom:15px;\">" +
                                  "<span class=\"dt\">" +
                                        "&nbsp;&nbsp;" + knowledgeItem.getReleaseDate() +
                                  "</span>" +
                                  "<span class=\"at\">发布者：" +
                                        "<!--<a href=\"/Web/DoctorInfo/36\">-->" + knowledgeItem.getAuthor() + "<!--</a>-->" +
                                        "</span>" +
                                        "&nbsp;&nbsp;|&nbsp;&nbsp;" +
                                  "<span class=\"vw\"><i class=\"pb-icons\"></i>" +
                                        "浏览" + "(" + knowledgeItem.getCount() + ")"  +
                                  "</span> " +
                                  "&nbsp;&nbsp;|&nbsp;&nbsp;" +
                            "</div>" +
                             knowledgeItem.getContent() +
                      "</body>" +
                "</html>";
    }

    @Override
    protected void onDestroy() {
        if (progressWebView != null) {
            progressWebView.stopLoading();
            progressWebView.removeAllViews();
            progressWebView.setWebViewClient(null);
            progressWebView.setWebChromeClient(null);
            unregisterForContextMenu(progressWebView);
            progressWebView.destroy();
        }
        super.onDestroy();
    }
}